package proxy

import (
	"fmt"
	"go-proxy/common"
	"go-proxy/config"
	"io"
	"net/http"
	"time"
)

var (
	checkClient = &http.Client{Timeout: 5 * time.Second}
)

func serverHealthCheck(r *http.Request) bool {
	path := r.URL.Path
	value := r.Header.Get(common.HealthCheckHeaderKey)
	method := r.Method
	common.LogTrace("serverHealthCheck host=", r.Host, " path=", path, " method=", method, " value=", value)
	return path == common.HealthCheckPath && method == "GET" && value == common.HealthCheckHeaderValue
}

func serverCheckStatus() {
	for {
		select {
		case <-time.After(5 * time.Second):
			common.LogTrace("Server health status check")
			proxyConfig := config.ProxyConfigData.Proxy
			for _, server := range proxyConfig.Servers {
				go doServerCheck(server)
			}
		}
	}
}

func doServerCheck(server config.ProxyServer) {
	name := server.Name
	msg := fmt.Sprintf("name=%s prot=%d", name, server.Port)
	// 创建一个新的 GET 请求
	checkUrl := fmt.Sprintf("http://localhost:%d%s", server.Port, common.HealthCheckPath)
	common.LogTrace(msg, " doServerCheck checkUrl:", checkUrl)
	req, err := http.NewRequest("GET", checkUrl, nil)
	if err != nil {
		common.LogError(msg, " Error creating request:", err)
		setServerStatus(name, false)
		return
	}

	// 添加自定义请求头
	req.Header.Set(common.HealthCheckHeaderKey, common.HealthCheckHeaderValue)

	// 发送请求
	resp, err := checkClient.Do(req)
	if err != nil {
		common.LogError(msg, " Error sending request err:", err)
		setServerStatus(name, false)
		return
	}
	defer func(Body io.ReadCloser) {
		err := Body.Close()
		if err != nil {
			common.LogError(msg, " Error sending request err:", err)
			setServerStatus(name, false)
		}
	}(resp.Body)

	// 检查响应状态码
	if resp.StatusCode == http.StatusOK {
		common.LogTrace(msg, " Server is up and running.")
		setServerStatus(name, true)
	} else {
		common.LogTrace(msg, " server returned status code: ", resp.StatusCode)
		setServerStatus(name, false)
	}
}
